import com.caucho.hessian.io.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by shuoGG on 2018/10/18
 */
public class Hessian2Util {
    private SerializerFactory serializerFactory;

    private Hessian2Util() {
        serializerFactory = SerializerFactory.createDefault();
    }

    private static class Hessian2UtilHolder {
        private static final Hessian2Util instance = new Hessian2Util();
    }

    public static Hessian2Util getInstance() {
        return Hessian2UtilHolder.instance;
    }

    public byte[] serialize(Object obj) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        Hessian2Output out = new Hessian2Output(bytes);
        out.setSerializerFactory(serializerFactory);
        try {
            out.writeObject(obj);
            out.close();
        } catch (IOException e) {
            throw new RuntimeException("IO错误", e);
        }
        return bytes.toByteArray();
    }

    public Object deserialize(byte[] data) {
        Hessian2Input in = new Hessian2Input(new ByteArrayInputStream(data));
        in.setSerializerFactory(serializerFactory);
        Object obj;
        try {
            obj = in.readObject();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException("IO错误", e);
        }
        return obj;
    }
}
